package com.lzb.compressmaster.fragment;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.king.image.imageviewer.ImageViewer;
import com.king.image.imageviewer.loader.GlideImageLoader;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lzb.compressmaster.BaseNoModelFragment;
import com.lzb.compressmaster.Content;
import com.lzb.compressmaster.R;
import com.lzb.compressmaster.activity.FileCompressActivity;
import com.lzb.compressmaster.activity.FileDecompressActivity;
import com.lzb.compressmaster.activity.PhoneStorageActivity;
import com.lzb.compressmaster.activity.SearchPrivacyActivity;
import com.lzb.compressmaster.activity.VideoPreviewActivity;
import com.lzb.compressmaster.adapter.DocumentsAdapter;
import com.lzb.compressmaster.basic.media.MediaInfo;
import com.lzb.compressmaster.databinding.FragmentCompressBinding;
import com.lzb.compressmaster.dialog.AddFolderDialog;
import com.lzb.compressmaster.dialog.AudioPreviewDialog;
import com.lzb.compressmaster.dialog.CopyDialog;
import com.lzb.compressmaster.dialog.DeleteDialog;
import com.lzb.compressmaster.dialog.FileEditDialog;
import com.lzb.compressmaster.dialog.MoreDialog;
import com.lzb.compressmaster.dialog.RenameDialog;
import com.lzb.compressmaster.dialog.SearchDialog;
import com.lzb.compressmaster.dialog.ViewPathDialog;
import com.lzb.compressmaster.utils.MimeUtils;
import com.lzb.compressmaster.utils.RxUtil;
import com.lzb.compressmaster.utils.StatusBarUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CompressFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CompressFragment extends BaseNoModelFragment<FragmentCompressBinding> implements View.OnClickListener, OnItemClickListener {

    public static String currentRootPath;
    private List<MediaInfo> listShow = new ArrayList<>();
    private List<String> listSel = new ArrayList<>();
    private DocumentsAdapter documentsAdapter;
    private String selPath;
    private boolean isEdit;
    private BasePopupView editPopup, morePopup;
    private FileEditDialog fileEditDialog;

    @Override
    protected int onCreate() {
        return R.layout.fragment_compress;
    }

    @Override
    protected void initView() {
        mDataBinding.ivEdit.setOnClickListener(this);
        mDataBinding.tvCancel.setOnClickListener(this);
        mDataBinding.tvAllSel.setOnClickListener(this);
        mDataBinding.tvDecompress.setOnClickListener(this);
        mDataBinding.tvCompress.setOnClickListener(this);
        mDataBinding.tvShare.setOnClickListener(this);
        mDataBinding.tvDelete.setOnClickListener(this);
        mDataBinding.tvMore.setOnClickListener(this);

        mDataBinding.rvFileList.setLayoutManager(new LinearLayoutManager(mContext));
        documentsAdapter = new DocumentsAdapter();
        mDataBinding.rvFileList.setAdapter(documentsAdapter);
        documentsAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ivEdit) {//编辑
            if (listShow.size() == 0) {
                ToastUtils.showShort(getString(R.string.no_file));
                return;
            }
            showEditDialog();
        } else if (id == R.id.tvCancel) {//取消编辑
            cancelEdit();
        } else if (id == R.id.tvAllSel) {//全选
            listSel.clear();
            for (MediaInfo mediaInfo : listShow) {
                mediaInfo.setSelected(true);
                listSel.add(mediaInfo.getPath());
            }
            documentsAdapter.setList(listShow);
        } else if (id == R.id.tvDecompress) {//解压
            if (listSel.size() == 0) {
                ToastUtils.showShort(getString(R.string.please_sel_file));
                return;
            }
            FileDecompressActivity.listPath = listSel;
            startActivity(FileDecompressActivity.class);
        } else if (id == R.id.tvCompress) {//压缩
            if (listSel.size() == 0) {
                ToastUtils.showShort(getString(R.string.please_sel_file));
                return;
            }
            FileCompressActivity.listPath = listSel;
            startActivity(FileCompressActivity.class);
        } else if (id == R.id.tvShare) {//分享
            if (listSel.size() == 0) {
                ToastUtils.showShort(getString(R.string.please_sel_file));
                return;
            }
            shareFiles();
        } else if (id == R.id.tvDelete) {//删除
            if (listSel.size() == 0) {
                ToastUtils.showShort(getString(R.string.please_sel_file));
                return;
            }
            showDeleteDialog();
        } else if (id == R.id.tvMore) {//更多
            showMoreDialog();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (documentsAdapter.getItem(position).isSelected()) {
                documentsAdapter.getItem(position).setSelected(false);
                listSel.remove(documentsAdapter.getItem(position).getPath());
            } else {
                documentsAdapter.getItem(position).setSelected(true);
                listSel.add(documentsAdapter.getItem(position).getPath());
            }
            documentsAdapter.notifyItemChanged(position);
            mDataBinding.tvSelNum.setText(getString(R.string.file_sel_num, listSel.size()));
        } else {
            String path = documentsAdapter.getItem(position).getPath();
            if (FileUtils.isDir(path)) {
                Intent intent = new Intent(getActivity(), PhoneStorageActivity.class);
                intent.putExtra(Content.path, path);
                startActivity(intent);
            } else if (MimeUtils.isImgMimeType(path)) {
                ImageViewer.load(path)//要加载的图片数据，单张或多张
                        .imageLoader(new GlideImageLoader())// 图片加载器，目前内置的有CoilImageLoader、GlideImageLoader和PicassoImageLoader，也可以自己实现
                        .selection(position)//当前选中位置，默认：0
                        .showIndicator(true)//是否显示指示器，默认不显示
                        .theme(com.king.image.imageviewer.R.style.ImageViewerTheme)//设置主题风格，默认：R.style.ImageViewerTheme
                        .orientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//设置屏幕方向,默认：ActivityInfo.SCREEN_ORIENTATION_BEHIND
                        .start(this);//activity or fragment, 跳转时的共享元素视图
            } else if (MimeUtils.isVideoMimeType(path)) {
                VideoPreviewActivity.sVideoPath = path;
                startActivity(VideoPreviewActivity.class);
            } else if (MimeUtils.isAudioMimeType(path)) {
                showAudioPreviewDialog(path);
            } else {
                gotoPreview(UriUtils.file2Uri(new File(path)));
            }
        }
    }

    @Override
    protected void initData() {
        //设置状态栏字体颜色
        StatusBarUtils.setSystemStatusTextColor(true, getActivity());
        currentRootPath = PathUtils.getExternalDocumentsPath() + Content.myCompressFile;
        getData(currentRootPath);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //设置状态栏字体颜色
            StatusBarUtils.setSystemStatusTextColor(false, getActivity());
        } else {
            //设置状态栏字体颜色
            StatusBarUtils.setSystemStatusTextColor(true, getActivity());
            getData(currentRootPath);
        }
    }

    private void getData(String rootPath) {
        listShow.clear();
        List<File> files = FileUtils.listFilesInDir(rootPath);
        if (files.size() == 0) {
            mDataBinding.flFileNoData.setVisibility(View.VISIBLE);
            mDataBinding.rvFileList.setVisibility(View.GONE);
        } else {
            mDataBinding.flFileNoData.setVisibility(View.GONE);
            mDataBinding.rvFileList.setVisibility(View.VISIBLE);
            for (File file : files) {
                listShow.add(new MediaInfo(file.getPath(), file.getName(), file.length(),
                        FileUtils.getFileLastModified(file), null, null));
            }
            mDataBinding.rvFileList.scrollToPosition(0);
            documentsAdapter.setList(listShow);
        }
    }

    private void addFolder(String name) {
        File file = new File(currentRootPath, name);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (mkdirs) {
                ToastUtils.showShort(R.string.add_dir_s);
                getData(currentRootPath);
            } else {
                ToastUtils.showShort(R.string.add_dir_s);
            }
        } else {
            ToastUtils.showShort(R.string.is_dir);
        }
    }

    /**
     * 获取文件的MIME类型
     */
    private String getMimeType(Uri uri) {
        String mimeType = getActivity().getContentResolver().getType(uri);
        if (TextUtils.isEmpty(mimeType)) {
            mimeType = "*/*";
        }
        return mimeType;
    }

    /**
     * 分享文件（单个或多个）
     */
    private void shareFiles() {
        if (listSel.isEmpty()) {
            ToastUtils.showShort("请选择要分享的文件");
            return;
        }

        try {
            ArrayList<Uri> fileUris = new ArrayList<>();

            // 收集所有选中文件的URI
            for (String filePath : listSel) {
                File file = new File(filePath);
                if (file.exists()) {
                    Uri fileUri = androidx.core.content.FileProvider.getUriForFile(
                            mContext,
                            "com.lzb.compressmaster.fileprovider",
                            file
                    );
                    fileUris.add(fileUri);
                }
            }

            if (fileUris.isEmpty()) {
                ToastUtils.showShort("没有可分享的文件");
                return;
            }

            Intent shareIntent;

            if (fileUris.size() == 1) {
                // 单个文件分享
                shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType(getMimeType(fileUris.get(0)));
                shareIntent.putExtra(Intent.EXTRA_STREAM, fileUris.get(0));
            } else {
                // 多个文件分享
                shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                shareIntent.setType("*/*");
                shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, fileUris);
            }

            // 设置权限
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            // 检查是否有可处理的应用
            List<ResolveInfo> resolveInfos = getActivity().getPackageManager().queryIntentActivities(shareIntent, 0);
            if (resolveInfos != null && !resolveInfos.isEmpty()) {
                startActivity(Intent.createChooser(shareIntent, "分享文件"));
            } else {
                ToastUtils.showShort("没有可分享的应用");
            }

        } catch (Exception e) {
            ToastUtils.showShort("分享失败: " + e.getMessage());
        }
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        for (String path : listSel) {
                            FileUtils.delete(path);
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                        cancelEdit();
                    }
                });
            }
        }, 1000);
    }

    private void copy(String path) {
        showDialog(getString(R.string.copy_ing));
        for (String selPath : listSel) {
            File sourceFile = new File(selPath);
            File destinationFolder = new File(path);
            // 如果目标文件夹不存在，则创建它
            if (!destinationFolder.exists()) {
                destinationFolder.mkdirs();
            }
            // 构造目标文件路径
            File destinationFile = new File(destinationFolder.getPath() + File.separator + sourceFile.getName());
            FileUtils.copy(sourceFile, destinationFile);
        }
        dismissDialog();
        ToastUtils.showShort(R.string.copy_suc);
        cancelEdit();
    }

    private void cut(String path) {
        showDialog(getString(R.string.move_ing));
        for (String selPath : listSel) {
            FileUtils.move(selPath, path + "/" + FileUtils.getFileName(selPath));
        }
        dismissDialog();
        ToastUtils.showShort(R.string.move_suc);
        cancelEdit();
    }

    private void cancelEdit() {
        isEdit = false;
        listSel.clear();
        mDataBinding.rlBack.setVisibility(View.VISIBLE);
        mDataBinding.rlEdit.setVisibility(View.INVISIBLE);
        mDataBinding.llBottom.setVisibility(View.GONE);
        documentsAdapter.setEdit(isEdit);
        getData(currentRootPath);
    }

    private void showEditDialog() {
        if (fileEditDialog == null) fileEditDialog = new FileEditDialog(mContext);
        fileEditDialog.setHideAdd(true);
        editPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivEdit).hasShadowBg(false) // 去掉半透明背景
                .asCustom(fileEditDialog);
        fileEditDialog.setListener(new FileEditDialog.Ilistener() {
            @Override
            public void clickEdit() {
                isEdit = true;
                mDataBinding.tvSelNum.setText(getString(R.string.file_sel_num, listSel.size()));
                mDataBinding.rlBack.setVisibility(View.INVISIBLE);
                mDataBinding.rlEdit.setVisibility(View.VISIBLE);
                mDataBinding.llBottom.setVisibility(View.VISIBLE);
                documentsAdapter.setEdit(isEdit);
                documentsAdapter.notifyDataSetChanged();
            }

            @Override
            public void clickAdd() {
                showAddFolderDialog();
            }
        });
        editPopup.show();
    }

    private void showSearchDialog() {
        SearchDialog searchDialog = new SearchDialog(mContext);
        searchDialog.setListener(new SearchDialog.Ilistener() {
            @Override
            public void clickSearch(String name) {
                SearchPrivacyActivity.keyword = name;
                startActivity(SearchPrivacyActivity.class);
            }
        });
        searchDialog.show();
    }

    private void showAddFolderDialog() {
        AddFolderDialog addFolderDialog = new AddFolderDialog(mContext);
        addFolderDialog.setListener(new AddFolderDialog.Ilistener() {
            @Override
            public void clickAddFolder(String name) {
                addFolder(name);
            }
        });
        addFolderDialog.show();
    }

    private void showDeleteDialog() {
        DeleteDialog deleteDialog = new DeleteDialog(mContext);
        deleteDialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                delete();
            }
        });
        deleteDialog.show();
    }

    private void showRenameDialog() {
        selPath = listSel.get(0);
        RenameDialog renameDialog = new RenameDialog(mContext);
        renameDialog.setName(FileUtils.getFileNameNoExtension(selPath));
        renameDialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                listSel.clear();
                FileUtils.rename(selPath, name + ((FileUtils.isDir(selPath)) ? "" : "." + FileUtils.getFileExtension(selPath)));
                getData(currentRootPath);
            }
        });
        renameDialog.show();
    }

    private void showMoreDialog() {
        MoreDialog moreDialog = new MoreDialog(mContext);
        moreDialog.setShowRename(listSel.size() == 1 ? true : false);
        morePopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Top) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.llBottom).hasShadowBg(false) // 去掉半透明背景
                .asCustom(moreDialog);
        moreDialog.setListener(new MoreDialog.Ilistener() {
            @Override
            public void clickCopy() {
                showCopyDialog(true);
            }

            @Override
            public void clickMove() {
                showCopyDialog(false);
            }

            @Override
            public void clickRename() {
                showRenameDialog();
            }

            @Override
            public void clickEncryption() {
                delete();
            }

            @Override
            public void clickViewPath() {
                showViewPathDialog();
            }
        });
        morePopup.show();
    }

    private void showCopyDialog(boolean isCopy) {
        CopyDialog copyDialog = new CopyDialog(mContext);
        copyDialog.setCopy(isCopy);
        copyDialog.setListener(new CopyDialog.Ilistener() {
            @Override
            public void clickCopy(String path) {
                copy(path);
            }

            @Override
            public void clickMove(String path) {
                cut(path);
            }
        });
        copyDialog.show();
    }

    private void showViewPathDialog() {
        selPath = listSel.get(0);
        ViewPathDialog viewPathDialog = new ViewPathDialog(mContext);
        viewPathDialog.setPath(selPath);
        viewPathDialog.show();
    }

    private void showAudioPreviewDialog(String path) {
        AudioPreviewDialog audioPreviewDialog = new AudioPreviewDialog(mContext);
        audioPreviewDialog.setAudioPath(path);
        audioPreviewDialog.show();
    }

    //跳转到预览应用
    private void gotoPreview(Uri selUri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(selUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        List<ResolveInfo> resolveInfos = getActivity().getPackageManager().queryIntentActivities(intent, 0);
        if (resolveInfos != null && !resolveInfos.isEmpty()) {
            startActivity(intent);
        } else {
            ToastUtils.showShort(R.string.no_preview_app);
        }
    }
}